package system;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.xml.internal.bind.v2.runtime.Name;

@WebServlet("/talkingRoom")
public class talkingRoom extends HttpServlet{
	private static final long serialVersionUID = 1L;
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String name=req.getParameter("name");
		String content=req.getParameter("content");
		int sex=Integer.parseInt(req.getParameter("sex"));
		int operate=Integer.parseInt(req.getParameter("operate"));
		int row=Integer.parseInt(req.getParameter("row"));
		int count=0;
		
		SimpleDateFormat no=new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Date d= new Date();
        String content_time=no.format(d); 
        
        String result="";
        
        sqlOperation sql = new sqlOperation();
        
        if(operate==1) {
        	boolean  insert=false;
        	int m=sql.getInsert("\"insert into talking values('\"+name+\"','\"+content+\"','\"+sex+\"','\"+content_time+\"')\"");

    		if(m!=0){
    			insert=true;			
    		}
    		count=sql.getCount("select COUNT(*) from talking");
    		result = "{\"code\":\""+insert+"\",\"count\":\""+count+"\"}"; 	
        }else if(operate==2) {  	
    		count=sql.getCount("select COUNT(*) from talking");
    		result = "{\"count\":\""+count+"\"}";
        }else if(operate==3) {
        	
    		String[] value=sql.getQueryLine("select * from talking order by time",3);
    		while(index<row) {
    			index+=1;
    			rs.next();
    			for(int i=0;i<3;i++){
    				value[i]=rs.getString(i+1);
    				
    				}
    			
    		}
    		result = "{\"name\":\""+value[0]+"\",\"content\":\""+value[1]+"\",\"sex\":\""+value[2]+"\"}";
    		con.close();
    	}

        }
        
	
    resp.setContentType("application/json;charset=UTF-8");
	PrintWriter out = resp.getWriter();		
	out.write(result);

	
	}
}


